﻿@implements IDisposable
@using Microsoft.JSInterop
@using Radzen.Blazor.Rendering
@inject IJSRuntime JSRuntime

@foreach (var dialog in dialogs)
{
    <DialogContainer Dialog=@dialog />
}

@code {
    [Inject] 
    DialogService Service { get; set; }

    List<Dialog> dialogs = new List<Dialog>();

    public async Task Open(string title, Type type, Dictionary<string, object> parameters, DialogOptions options)
    {
        dialogs.Add(new Dialog() { Title = title, Type = type, Parameters = parameters, Options = options });

        await InvokeAsync(() => { StateHasChanged(); });

        await JSRuntime.InvokeAsync<string>("Radzen.openDialog");
    }

    public async Task Close(dynamic result)
    {
        var lastDialog = dialogs.LastOrDefault();
        if (lastDialog != null)
        {
            dialogs.Remove(lastDialog);
            await JSRuntime.InvokeAsync<string>("Radzen.closeDialog");
        }

        await InvokeAsync(() => 
        { 
            StateHasChanged(); 
        });
    }

    public void Dispose()
    {
        Service.OnOpen -= OnOpen;
        Service.OnClose -= OnClose;
        Service.OnRefresh -= OnRefresh;
    }

    protected override void OnInitialized()
    {
        Service.OnOpen += OnOpen;
        Service.OnClose += OnClose;
        Service.OnRefresh += OnRefresh;
    }

    void OnOpen(string title, Type type, Dictionary<string, object> parameters, DialogOptions options)
    {
        Open(title, type, parameters, options).ConfigureAwait(false);
    }

    void OnClose(dynamic result)
    {
        Close(result).ConfigureAwait(false);
    }

    void OnRefresh()
    {
        InvokeAsync(StateHasChanged).ConfigureAwait(false);
    }
}